<template>
  <div class="attraction-panel" :class="{ 'panel-minimized': isMinimized }">
    <div class="panel-header">
      <div class="panel-title">福州景点推荐</div>
      <div class="panel-actions">

        <button class="btn" title="关闭" @click="closePanel">
          <i class="fas fa-times"></i>
        </button>
      </div>
    </div>

    <div class="search-box" v-if="!isMinimized">
      <div class="search-container">
        <input type="text" class="search-input" placeholder="搜索福州景点..." v-model="searchQuery"
          @keyup.enter="performSearch">
        <button class="search-btn" @click="performSearch">
          <i class="fas fa-search"></i>
        </button>
      </div>
    </div>

    <div class="categories" v-if="!isMinimized">
      <div v-for="category in categories" :key="category.id"
        :class="['category', { active: selectedCategory === category.id }]" @click="selectCategory(category.id)">
        {{ category.name }}
      </div>
    </div>

    <div class="attractions-list" v-if="!isMinimized">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-state">
        <i class="fas fa-spinner fa-spin"></i>
        <span>正在搜索中...</span>
      </div>

      <!-- 错误信息 -->
      <div v-else-if="errorMessage" class="error-state">
        <i class="fas fa-exclamation-triangle"></i>
        <span>{{ errorMessage }}</span>
      </div>

      <!-- 无结果 -->
      <div v-else-if="filteredAttractions.length === 0 && searchQuery" class="empty-state">
        <i class="fas fa-search"></i>
        <span>未找到相关景点</span>
      </div>

      <!-- 搜索结果 -->
      <AttractionItem v-for="attraction in filteredAttractions" :key="attraction.id" :attraction="attraction"
        @toggle-favorite="toggleFavorite" @item-clicked="handleItemClick" />
    </div>
  </div>
</template>

<script>
import AttractionItem from './AttractionItem.vue'
export default {
  name: 'AttractionPanel',
  components: {
    AttractionItem
  },
  props: {
    attractions: {
      type: Array,
      required: true
    },
    // 添加地图实例作为 prop
    map: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      searchQuery: '',
      selectedCategory: 'all',
      categories: [
        { id: 'all', name: '全部' },
        { id: '历史文化', name: '历史文化' },
        { id: '自然风光', name: '自然风光' },
        { id: '寺庙古刹', name: '寺庙古刹' },
        { id: '公园休闲', name: '公园休闲' },
        { id: '古镇街区', name: '古镇街区' }
      ],
      isMinimized: false,
      loading: false,
      searchResults: [],
      errorMessage: '',
      currentMarker: null,
      currentInfoWindow: null
    }
  },
  computed: {
    filteredAttractions() {
      // 使用当前可用的数据：先检查搜索结果，如果没有则使用props中的默认数据
      const sourceData = this.searchResults.length > 0 ? this.searchResults : this.attractions
      let filtered = [...sourceData] // 创建副本避免直接修改props

      // 按分类筛选
      if (this.selectedCategory !== 'all') {
        filtered = filtered.filter(attr => attr.category === this.selectedCategory)
      }

      // // 如果有搜索词且没有API搜索结果，在默认数据中本地搜索
      // if (this.searchQuery && this.searchResults.length === 0) {
      //   const query = this.searchQuery.toLowerCase()
      //   filtered = filtered.filter(attr =>
      //     attr.name.toLowerCase().includes(query) ||
      //     (attr.description && attr.description.toLowerCase().includes(query))
      //   )
      // }

      return filtered
    }
  },
  methods: {
    closePanel() {
      this.$emit('panel-closed')
    },
    toggleMinimize() {
      this.isMinimized = !this.isMinimized
      this.$emit('panel-minimized', this.isMinimized)
    },
    selectCategory(categoryId) {
      this.selectedCategory = categoryId
    },
    performSearch() {
      // 1. 获取搜索关键词
      console.log("执行景点搜索");

      const query = this.searchQuery?.trim();
      if (!query) {
        this.searchResults = [];
        this.errorMessage = '';
        return;
      }

      // 2. 配置请求参数
      const key = '73620a87372207565f51ea53f3f3108c';
      const city = '福州';
      const url = 'https://restapi.amap.com/v3/place/text';

      // 构造查询参数
      const params = new URLSearchParams({
        key,
        keywords: query,
        city,
        citylimit: 'true',
        children: '0',
        offset: '20',
        page: '1',
        extensions: 'base',
        output: 'json'
      });

      // 3. 显示加载状态
      this.loading = true;
      this.searchResults = [];
      this.errorMessage = '';

      // 4. 发送请求
      fetch(`${url}?${params}`)
        .then(res => res.json())
        .then(data => {
          if (data.status === '1' && data.count > '0') {
            // 成功获取数据
            this.searchResults = data.pois.map(poi => ({
              id: poi.id,
              name: poi.name,
              address: poi.address || '地址信息暂无',
              location: poi.location,
              type: poi.type,
              tel: poi.tel || '暂无',
              province: poi.pname,
              city: poi.cityname,
              area: poi.adname,
              category: this.getCategoryFromType(poi.type),
              description: this.generateDescription(poi),
              rating: this.generateRandomRating()
            }));
            console.log("搜索结果:", this.searchResults);
          } else {
            this.searchResults = [];
            this.errorMessage = data.info || '未找到相关结果';
          }
        })
        .catch(err => {
          console.error('搜索请求失败:', err);
          this.errorMessage = '网络错误，无法连接到地图服务';
          this.searchResults = [];
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    // 飞向指定位置并添加红色标记
    flyToLocation(spot) {
      // 确保地图实例存在
      if (!this.map) {
        console.warn('地图实例未提供');
        return;
      }

      try {
        // 解析经纬度 "119.306,26.075" → [lng, lat]
        const locationParts = spot.location.split(',');
        if (locationParts.length !== 2) {
          console.error('无效的位置信息:', spot.location);
          return;
        }

        const lng = parseFloat(locationParts[0]);
        const lat = parseFloat(locationParts[1]);

        if (isNaN(lng) || isNaN(lat)) {
          console.error('无效的经纬度:', spot.location);
          return;
        }

        // 清除之前的标记
        this.clearMarkers();

        // 创建红色标记
        const marker = new AMap.Marker({
          position: [lng, lat],
          icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png', // 红色标记
          title: spot.name,
          map: this.map
        });

        // 添加信息窗口
        const infoWindow = new AMap.InfoWindow({
          content: `<div style="padding: 5px;">
            <h3 style="margin: 0 0 5px 0; color: #e74c3c;">${spot.name}</h3>
          </div>`,
          offset: new AMap.Pixel(0, -30)
        });

        infoWindow.open(this.map, [lng, lat]);
        
        // 保存标记引用
        this.currentMarker = marker;
        this.currentInfoWindow = infoWindow;

        // 地图跳转并放大到指定位置
        this.map.setZoomAndCenter(16, [lng, lat]);
        
        console.log('已跳转到位置并添加红色标记:', spot.name, '经纬度:', [lng, lat]);
      } catch (error) {
        console.error('定位到景点时出错:', error);
      }
    },

    // 清除标记
    clearMarkers() {
      if (this.currentMarker) {
        this.currentMarker.setMap(null);
        this.currentMarker = null;
      }
      if (this.currentInfoWindow) {
        this.currentInfoWindow.close();
        this.currentInfoWindow = null;
      }
    },
    
    toggleFavorite(attractionId) {
      this.$emit('toggle-favorite', attractionId)
    },
    
    handleItemClick(attractionId) {
      // 根据 attractionId 找到对应的景点数据
      let spot = this.filteredAttractions.find(attr => attr.id === attractionId);
      
      if (spot) {
        // 调用飞向位置的方法
        this.flyToLocation(spot);
        // 同时触发 item-clicked 事件（如果父组件需要）
        this.$emit('item-clicked', attractionId);
      } else {
        console.warn('未找到ID为', attractionId, '的景点');
      }
    },
    
    // 根据类型推断分类
    getCategoryFromType(type) {
      if (!type) return '其他';
      
      const typeStr = type.toLowerCase();
      if (typeStr.includes('风景') || typeStr.includes('景点') || typeStr.includes('公园')) {
        return '自然风光';
      } else if (typeStr.includes('文化') || typeStr.includes('历史') || typeStr.includes('博物')) {
        return '历史文化';
      } else if (typeStr.includes('寺庙') || typeStr.includes('宗教') || typeStr.includes('教堂')) {
        return '寺庙古刹';
      } else if (typeStr.includes('古镇') || typeStr.includes('街区') || typeStr.includes('商业街')) {
        return '古镇街区';
      } else if (typeStr.includes('休闲') || typeStr.includes('娱乐') || typeStr.includes('体育')) {
        return '公园休闲';
      } else {
        return '其他';
      }
    },
    
    // 生成景点描述
    generateDescription(poi) {
      const { name, type, adname } = poi;
      const typeStr = this.formatType(type);
      
      return `${name}位于${adname}，是一个${typeStr}类型的景点，提供丰富的旅游体验和文化感受。`;
    },
    
    // 格式化类型显示
    formatType(type) {
      if (!type) return '旅游';
      return type.split(';').pop().replace('相关', '').replace('服务', '') || '旅游';
    },
    
    // 生成随机评分（4.0-5.0之间）
    generateRandomRating() {
      return (Math.random() * 1 + 4).toFixed(1);
    }
  }
}
</script>

<style scoped>
.attraction-panel {
  width: 500px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
}

.panel-header {
  padding: 15px 20px;
  background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.panel-title {
  font-size: 1.3rem;
  font-weight: 600;
}

.panel-actions {
  display: flex;
  gap: 10px;
}

.btn {
  background: rgba(255, 255, 255, 0.2);
  border: none;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: scale(1.1);
}

.search-box {
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.search-container {
  display: flex;
  background: white;
  border-radius: 30px;
  overflow: hidden;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1);
}

.search-input {
  flex: 1;
  border: none;
  padding: 12px 20px;
  outline: none;
  font-size: 1rem;
}

.search-btn {
  background: var(--primary-color);
  color: white;
  border: none;
  padding: 0 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.search-btn:hover {
  background: #2980b9;
}

.categories {
  display: flex;
  padding: 10px 15px;
  gap: 8px;
  overflow-x: auto;
  border-bottom: 1px solid #eee;
}

.category {
  padding: 6px 15px;
  background: #f1f1f1;
  border-radius: 20px;
  font-size: 0.9rem;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.category.active {
  background: var(--primary-color);
  color: white;
}

.category:hover {
  background: #ddd;
}

.category.active:hover {
  background: #2980b9;
}

.attractions-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

/* 状态样式 */
.loading-state,
.error-state,
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  color: #6b7280;
  text-align: center;
}

.loading-state i,
.error-state i,
.empty-state i {
  font-size: 2rem;
  margin-bottom: 16px;
  color: var(--primary-color);
}

.error-state i {
  color: #ef4444;
}

.empty-state i {
  color: #9ca3af;
}

.loading-state span,
.error-state span,
.empty-state span {
  font-size: 1rem;
  line-height: 1.5;
}

/* 最小化状态样式 */
.panel-minimized {
  width: 250px;
}

.panel-minimized .search-box,
.panel-minimized .categories,
.panel-minimized .attractions-list {
  display: none;
}

@media (max-width: 900px) {
  .attraction-panel {
    width: 100%;
  }

  .panel-minimized {
    width: 100%;
  }
}
</style>